package com.lucenly.card;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.lucenly.card.activity.LoginActivity;
import com.lucenly.card.base.ActivityManager;
import com.lucenly.card.base.BaseActivity;
import com.lucenly.card.bean.UserInfo;
import com.lucenly.card.constants.UrlDefend;
import com.lucenly.card.event.StringMsgEvent;
import com.lucenly.card.fragment.AcountFragment;
import com.lucenly.card.fragment.HomeFragment;
import com.lucenly.card.fragment.HomeNewFragment;
import com.lucenly.card.fragment.InvitationFragment;
import com.lucenly.card.fragment.RankFragment;
import com.lucenly.card.utils.PhoneInfo;
import com.lucenly.card.view.NavigateTabBar;
import com.lucenly.card.view.dialog.UpDataDialog;
import com.lucenly.card.view.dialog.UpDataDialog2;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.event.IEvent;
import com.vise.xsnow.event.Subscribe;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.utls.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity implements NavigateTabBar.OnTabSelectedListener{
    private static final String TAG_HOME="首页";
    private static final String TAG_RANK="打卡排行";
    private static final String TAG_INVITATION="邀请好友";
    private static final String TAG_ACOUNT="个人中心";
    @BindView(R.id.mainTabBar)
    NavigateTabBar mainTabBar;
    private int[] iconId = {R.mipmap.ic_home_select,R.mipmap.ic_home,R.mipmap.ic_rank_select,R.mipmap.ic_rank,
    R.mipmap.ic_yq_select,R.mipmap.ic_yq,R.mipmap.ic_my_select,R.mipmap.ic_my};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    protected void initView() {
        mainTabBar.addTab(HomeFragment.class,new NavigateTabBar.TabParam(iconId[1],iconId[0],TAG_HOME));
        mainTabBar.addTab(RankFragment.class,new NavigateTabBar.TabParam(iconId[3],iconId[2],TAG_RANK));
        mainTabBar.addTab(InvitationFragment.class,new NavigateTabBar.TabParam(iconId[5],iconId[4],TAG_INVITATION));
        mainTabBar.addTab(AcountFragment.class,new NavigateTabBar.TabParam(iconId[7],iconId[6],TAG_ACOUNT));
        mainTabBar.setTabSelectListener(this);
    }

    @Override
    protected void bindEvent() {

    }

    @Override
    protected void initData() {
        getUser();
        checkUpdata();
    }

    /**
     * 检查更新
     */
    private void checkUpdata() {

        ViseHttp.GET(UrlDefend.CHECK_UPDATA)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .addParam("os","2")
                .addParam("versionNum",PhoneInfo.getInstance(MainActivity.this).getVerCode()+"")
                .request(new ACallback<String>() {

                    @Override
                    public void onSuccess(String data) {
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            int isForce = jsonObject.getInt("isForce");
                            boolean isCancel = true;
                            if(isForce==1){
                                isCancel = false;
                            }
                            UpDataDialog2 upDataDialog = new UpDataDialog2(MainActivity.this,isCancel);
                            upDataDialog.show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
//                        ToastUtil.showSingletonShort(errMsg);
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("Main===","onresume");
    }
    @Override
    protected boolean isRegisterEvent() {
        return true;
    }
    @Subscribe
    public void login(IEvent iEvent){
        if(iEvent!=null && iEvent instanceof StringMsgEvent){
            if(((StringMsgEvent) iEvent).getMsg().equals("login")){
                getUser();
            }else if(((StringMsgEvent) iEvent).getMsg().equals("selectTab")){
                mainTabBar.setCurrentSelectedTab(0);
            }
        }
    }
    private void getUser() {
        ViseHttp.GET(UrlDefend.GET_INFO)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .request(new ACallback<UserInfo>() {
                    @Override
                    public void onSuccess(UserInfo data) {
                        JPushInterface.setAlias(MainActivity.this,1,data.getId()+"");
                        SharedPreferencesUtil.getInstance().putObject("user",data);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
//                        ToastUtil.showSingletonShort(errMsg);
                        SharedPreferencesUtil.getInstance().putObject("user",null);
                    }
                });
    }

    @Override
    protected void processClick(View view) {

    }

    @Override
    public void onTabSelected(NavigateTabBar.ViewHolder holder) {
        switch (holder.tabIndex){
            case 0:
                mainTabBar.showFragment(holder);
//                Sofia.with(MainActivity.this).statusBarBackground(getResources().getColor(R.color.color_transparent)).invasionStatusBar().statusBarLightFont();
                break;
            case 1:
                BusManager.getBus().post(new StringMsgEvent("tab"));
                mainTabBar.showFragment(holder);
                break;
            case 2:
                UserInfo user = SharedPreferencesUtil.getInstance().getObject("user", UserInfo.class);
                if(user==null){
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }else{
                    BusManager.getBus().post(new StringMsgEvent("tab"));
                    mainTabBar.showFragment(holder);
                }
                break;
            case 3:
                UserInfo user2 = SharedPreferencesUtil.getInstance().getObject("user", UserInfo.class);
                if(user2==null){
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }else{
                    BusManager.getBus().post(new StringMsgEvent("tab"));
                    mainTabBar.showFragment(holder);
                }
//                Sofia.with(this).statusBarBackground(getResources().getColor(R.color.colorPrimary)).statusBarLightFont();
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    private long exitTime = 0;
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(MainActivity.this,"再按一次退出程序！",Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            ActivityManager.getInstance().appExit(this);
        }
    }
}
